package checkFile;

import org.apache.tomcat.util.buf.HexUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 校验文件是否相同 通过文件摘要方式
 * @date 2021年12月04日 18:07
 * @description 原文地址https://mp.weixin.qq.com/s?__biz=MzAxODcyNjEzNQ==&mid=2247547666&idx=2&sn=b80bc1797a84202e27ba8a06d34061d0&chksm=9bd3968aaca41f9c19ae47b7a829cc3551785df6255c01540793b376976554af84ef9cba54bd&mpshare=1&scene=24&srcid=1204l0wgNQqGhcSUpBpacKep&sharer_sharetime=1638600726259&sharer_shareid=4e70123152a142f12badd70bdb2513fb#rd
 */
public class CheckFile {


    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
        String path1 = "C:\\Users\\KiroLox\\Desktop\\HTTP_Server_Log.txt";
        String path2 = "C:\\Users\\KiroLox\\Desktop\\HTTP_Server_Log (1).txt";

        String checksum1 = extractChecksum(path1, "MD5");
        String checksum2 = extractChecksum(path2, "MD5");
        System.out.println(checksum1.equals(checksum2));
    }


    /**
     * 提取文件 checksum
     * @param path 文件全路径
     * @param algorithm  算法名 例如 MD5、SHA-1、SHA-256、MD2、SHA-384、SHA-512、HmacMD5等
     * @return checkSum
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
    public static String extractChecksum(String path,String algorithm) throws NoSuchAlgorithmException, IOException {

        //根据算法名称初始化摘要算法
        MessageDigest instance = MessageDigest.getInstance(algorithm);

        //读取文件所有比特
        byte[] bytes = Files.readAllBytes(Paths.get(path));

        //摘要更新
        instance.update(bytes);

        //完成哈希摘要计算并返回特征值
        byte[] digest = instance.digest();

        // 进行十六进制的输出
        return HexUtils.toHexString(digest);

    }
}
